import { Exceptions } from "./../kalend";

/**
 * 超时验证
 * @param delay 间隔时间
 * @param options 参数配置
 */
export const timeout = (delay: number, options: { message?: string } = {}) => async (_: any, next: Function) => {
    const message = options.message || '请求超时';
    let timer;
    const timeout = new Promise((_, reject) => {
        timer = setTimeout(() => {
            try {
                throw Exceptions.known(message);
            } catch (error) {
                reject(error);
            }
        }, delay);
        clearTimeout(timer);
    });
    await Promise.race([timeout, next()]);
    clearTimeout(timer);
}